/**
 * 图片URL处理辅助工具
 * 用于解决图片上传和显示问题
 */
 
// 全局变量，存储已上传的图片URL
window.uploadedImages = window.uploadedImages || {};

/**
 * 修复图片URL问题
 * @param {String} originalUrl 原始URL
 * @returns {String} 修复后的URL
 */
function fixImageUrl(originalUrl) {
    // 如果是Upload目录下的图片
    if (originalUrl && originalUrl.startsWith("/upload/images/")) {
        // 解析路径
        var parts = originalUrl.split("/");
        if (parts.length >= 4) {
            var date = parts[2];
            var filename = parts[3];
            
            // 尝试几种不同的URL格式以增加成功率
            // 1. 使用静态资源路径 
            return "/static/upload/images/" + date + "/" + filename;
        }
    }
    return originalUrl;
}

/**
 * 获取备用图片URL列表
 * @param {String} originalUrl 原始URL
 * @returns {Array} 备用URL列表
 */
function getBackupImageUrls(originalUrl) {
    var backupUrls = [];
    
    // 始终添加原始URL作为第一个选项
    backupUrls.push(originalUrl);
    
    if (originalUrl && originalUrl.startsWith("/upload/images/")) {
        // 解析路径
        var parts = originalUrl.split("/");
        if (parts.length >= 4) {
            var date = parts[2];
            var filename = parts[3];
            
            // 添加各种可能的URL格式
            backupUrls.push("/static/upload/images/" + date + "/" + filename);  // 静态资源路径
            backupUrls.push("/upload/file/" + date + "/" + filename);           // 直接访问端点
            backupUrls.push("/upload/images/" + date + "/" + filename);         // 原始路径
            backupUrls.push("upload/images/" + date + "/" + filename);          // 相对路径
            backupUrls.push("/static/" + originalUrl);                          // 静态资源前缀
            backupUrls.push(window.location.origin + originalUrl);              // 完整URL
            backupUrls.push(window.location.origin + "/static" + originalUrl);  // 完整URL+静态资源
            backupUrls.push(window.location.origin + "/upload/file/" + date + "/" + filename); // 完整URL+直接端点
        }
    }
    
    // 删除重复项
    return [...new Set(backupUrls)];
}

/**
 * 记录上传的图片信息
 * @param {String} url 图片URL
 * @param {Object} metadata 元数据
 */
function registerUploadedImage(url, metadata) {
    if (url) {
        window.uploadedImages[url] = metadata || {
            timestamp: new Date().getTime(),
            backupUrls: getBackupImageUrls(url)
        };
    }
}

/**
 * 检查图片是否可访问
 * @param {String} url 图片URL
 * @param {Function} successCallback 成功回调
 * @param {Function} errorCallback 失败回调
 */
function checkImageAccessibility(url, successCallback, errorCallback) {
    if (!url) {
        if (errorCallback) errorCallback("URL为空");
        return;
    }
    
    console.log("检查图片可访问性:", url);
    
    // 获取所有可能的URL
    var backupUrls = getBackupImageUrls(url);
    console.log("备用URL列表:", backupUrls);
    
    // 保持追踪尝试次数
    var attemptCount = 0;
    var maxAttempts = backupUrls.length;
    var succeeded = false;
    
    // 尝试每个URL
    function tryNextUrl(index) {
        if (index >= maxAttempts || succeeded) {
            if (!succeeded && errorCallback) {
                errorCallback("所有URL尝试均失败");
            }
            return;
        }
        
        var currentUrl = backupUrls[index];
        console.log("尝试URL " + (index+1) + "/" + maxAttempts + ": " + currentUrl);
        
        // 添加时间戳防止缓存
        var timestampedUrl = currentUrl;
        if (timestampedUrl.indexOf("?") === -1) {
            timestampedUrl += "?t=" + new Date().getTime();
        } else {
            timestampedUrl += "&t=" + new Date().getTime();
        }
        
        var img = new Image();
        img.onload = function() {
            console.log("图片加载成功:", currentUrl);
            succeeded = true;
            if (successCallback) successCallback(currentUrl);
        };
        
        img.onerror = function() {
            console.log("图片加载失败:", currentUrl);
            attemptCount++;
            
            // 如果失败，尝试下一个URL
            setTimeout(function() {
                tryNextUrl(index + 1);
            }, 100); // 延迟100ms再尝试下一个
        };
        
        img.src = timestampedUrl;
    }
    
    // 开始尝试第一个URL
    tryNextUrl(0);
}

// 导出函数
window.fixImageUrl = fixImageUrl;
window.getBackupImageUrls = getBackupImageUrls;
window.registerUploadedImage = registerUploadedImage;
window.checkImageAccessibility = checkImageAccessibility; 